package com.cy.cy2025.service

import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.content.res.AssetFileDescriptor
import android.media.MediaPlayer
import android.os.Bundle
import android.os.IBinder
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LifecycleService
import com.cy.cy2025.IMusicAidlInterface
import com.cy.cy2025.databinding.ActivityCustomProcessServiceBinding
import com.cy.cy2025.entity.MusicInfo
import com.cy.cy2025.util.LogUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class CustomProcessService : LifecycleService() {
    private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)

    companion object {
        var musicPlayer: MediaPlayer? = null
    }

    var stopped = false

    val binder = object : IMusicAidlInterface.Stub() {

        override fun play() {
            runCatching {
                if (stopped) {
                    musicPlayer?.prepare()
                }
                musicPlayer?.start()
            }.onFailure {
                LogUtil.s("CustomProcessService", "执行play失败并重置：${it.stackTraceToString()}")
                reinitMediaPlayer()
                musicPlayer?.start()

            }
        }


        override fun stop() {
            runCatching {
                stopped = true
                musicPlayer?.stop()
            }.onFailure {
                LogUtil.s("CustomProcessService", "执行stop失败并重置：${it.stackTraceToString()}")
                reinitMediaPlayer()
            }
        }

        override fun pause() {
            runCatching {
                musicPlayer?.pause()
            }.onFailure {
                LogUtil.s("CustomProcessService", "执行pause失败并重置：${it.stackTraceToString()}")
                reinitMediaPlayer()
            }
        }

        override fun getMusicInfo(): MusicInfo? {
            return MusicInfo(
                "oynn",
                "assets/oynn.m4a"
            )
        }
    }


    var assetFd: AssetFileDescriptor? = null

    override fun onCreate() {
        super.onCreate()
        initMediaPlayer()
        serviceScope.launch {
            runCatching {
                while (true) {
                    LogUtil.s("CustomProcessService", "音乐service运行保持记录")
                    delay(1000 * 60)
                }
            }.onFailure {
                LogUtil.s(
                    "CustomProcessService",
                    "音乐service日志记录异常：${it.stackTraceToString()}"
                )
            }
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        serviceScope.cancel() // 取消所有子协程
        musicPlayer?.release() // 关键：释放 MediaPlayer，避免失控
    }

    private fun initMediaPlayer() {
        musicPlayer = MediaPlayer()
        assetFd = assets.openFd("oynn.m4a")
        // 测试音乐放在assets文件夹下，名为oynn.m4a
        musicPlayer?.setDataSource(
            assetFd!!.fileDescriptor,
            assetFd!!.startOffset,
            assetFd!!.length
        )
        assetFd!!.close()
        musicPlayer?.prepare()
        musicPlayer?.isLooping = true
    }

    private fun reinitMediaPlayer() {
        musicPlayer?.release()
        musicPlayer = null
        initMediaPlayer()
    }


    override fun onBind(intent: Intent): IBinder? {
        super.onBind(intent)
        return binder
    }

}


class CustomProcessServiceActivity : AppCompatActivity() {

    val binding by lazy {
        ActivityCustomProcessServiceBinding.inflate(layoutInflater)
    }

    var musicService: IMusicAidlInterface? = null

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        startService(Intent(this, CustomProcessService::class.java))
        bindService(Intent(this, CustomProcessService::class.java), object : ServiceConnection {
            override fun onServiceConnected(
                name: ComponentName?,
                service: IBinder?
            ) {
                musicService = IMusicAidlInterface.Stub.asInterface(service)

                val musicInfo = musicService?.musicInfo
                binding.tvInfo.text = musicInfo?.name + "\n\n" + musicInfo?.url
            }

            override fun onServiceDisconnected(name: ComponentName?) {
                musicService = null
            }

        }, BIND_AUTO_CREATE)

        binding.btnStart.setOnClickListener {
            musicService?.play()
        }
        binding.btnStop.setOnClickListener {
            musicService?.stop()
        }
        binding.btnPause.setOnClickListener {
            musicService?.pause()
        }
    }

}